import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import common from './common/common'
import {HeadersTokenKey} from "./common/constants";
import router from "./routers/index";
axios.defaults.timeout = 10*60*1000
let instance: AxiosInstance = null as never
const axiosInstance = () => {
    if (!instance) {
        instance = axios.create({
            baseURL: '',
            headers: { 'Content-Type': 'application/json' }, // x-www-form-urlencoded
            timeout: 120000
        })
    }
    instance.interceptors.request.use(
        (config: AxiosRequestConfig) => {
            config.headers = config.headers || {}
            const token = common.getLocalToken();
            if (token) {
                config.headers[HeadersTokenKey] = 'Bearer ' + token
            } else {
                if (config.url.indexOf('/login') < 0) {
                    router.replace('/login')
                    return Promise.reject('token不存在')
                }
            }
            return config
        },
        (error) => Promise.reject(error)
    )
    instance.interceptors.response.use(
        (response: AxiosResponse) => {
            const res = response.data
            if (!res) {
                return Promise.reject('后端接口连接异常')
            }
            if (res.errors && res.errors.length && res.errors[0].code === 'auth.authentication_invalid_token') {
                common.removeLocalToken()
                common.removeLocalUser()
                router.replace('/login')
                return Promise.reject('登录超时或未登录')
            }
            return Promise.resolve(res)
        },
        (error) => {
            const res = error.response
            if (res.data && res.data.errors && res.data.errors.length && res.data.errors[0].code === 'auth.authentication_invalid_token') {
                common.removeLocalToken()
                common.removeLocalUser()
                router.replace('/login')
                return Promise.reject('登录超时或未登录')
            }
            return Promise.reject(error?.response?.data)
        }
    )
    return instance
}
export default axiosInstance()
